package com.zxmr.webclient.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.zxmr.domain.account.User;
import com.zxmr.domain.file.File;
import com.zxmr.util.ResourceManager;
import com.zxmr.webclient.action.view.FileUploadResultView;
import com.zxmr.webclient.upload.UploadException;
import com.zxmr.webclient.upload.Uploader;
import com.zxmr.webclient.upload.UploaderFactory;

@Controller
public class FileUploader {

	@RequestMapping(value = "/file/upload", method = RequestMethod.POST)
	public @ResponseBody FileUploadResultView  upload(@RequestParam("type") String type,@RequestParam("cfile") MultipartFile cfile, HttpServletRequest request)
	{
		HttpSession session = request.getSession();
		User user = (User)session.getAttribute("user");
		FileUploadResultView view = new FileUploadResultView();
		if(user == null)
		{
			view.setError(1);
			view.setMessage(ResourceManager.getInstance().getMessage("com.client.nologin"));
			return view;
		}
		
	    if(cfile == null || cfile.isEmpty()){ 
	    	view.setError(1);
	    	view.setMessage(ResourceManager.getInstance().getMessage("com.client.nofile"));
			return view;
        }
	    if(cfile.getSize() > 2000000)
	    {
	    	view.setError(1);
	    	view.setMessage(ResourceManager.getInstance().getMessage("com.client.upload.size"));
			return view;
	    }
	    
        Uploader uploader = UploaderFactory.getUploader(type);
        if(uploader == null)
        {
	    	view.setError(1);
	    	view.setMessage(ResourceManager.getInstance().getMessage("com.client.upload.type"));
			return view;	
        }
        try {
			File file = uploader.upload(cfile, request);
		    view.setError(0);
		    view.setUrl("file/down?id="+file.getId());
		    view.setId(file.getId());
		    view.setName(file.getName());
		    return view;
		    	
		} catch (UploadException e) {
		    view.setError(1);
		    view.setMessage(e.getMessage());
			return view;
		}
	}
}
